package Network;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Vector;

import Wormish.agiletre.se.GameThread;

public class NetworkHandler
{
	//private GameThread mGameThread;
	public UdpClient client;
	public UdpServer server;
	public String mode = "Client";
	public static final int SERVER_PORT = 2008;
	public static final int CLIENT_PORT = 2008;
	public static int BYTE_SIZE = 2000;


	public NetworkHandler()
	{
	}

	public NetworkHandler(GameThread gameThread)
	{

		//mGameThread = gameThread;
		server = new UdpServer();
		//server.mSendPacket = new UdpPacket(new Vec2f(25f,25f), "Client");
		server.start();
		
		mode = "Server";
		//calculateSize();
	}
	
	public NetworkHandler(GameThread gameThread, String iNetAddress){

		//mGameThread = gameThread;
		client = new UdpClient(iNetAddress);	
	//	client.mSendPacket = new UdpPacket(new Vec2f(1f,1f), "Server");
		client.start();	
		//calculateSize();
		mode = "Client";
	}
	public Vector<byte[]> requestUpdate()
	{
		if(mode == "Server")
		{
			return server.GetReceivedPackets();
		}
		else
		{
			return client.GetReceivedPackets();
		}
	}
	public void sendUpdate(UdpPacket packet){
		//Log.d("NetworkHandler", " " + packet.AnimationState + " " + packet.Pos);
		if(mode == "Server")
			server.mSendPacket = packet;
		else
			client.mSendPacket = packet;
	}
	
	public static byte[] Serialize(UdpPacket packet)
	{
		// Serialize to a byte array
		ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
		ObjectOutputStream out;

		try
		{
			out = new ObjectOutputStream(bos);
			out.writeObject(packet);
			out.close();
		}
		catch (IOException e1)
		{
			e1.printStackTrace();
		}

		// Get the bytes of the serialized object
		return bos.toByteArray();
	}

	public static UdpPacket Deserialize(byte[] data)
	{
		ObjectInputStream iStream;
		UdpPacket packet = null;

		try
		{
			iStream = new ObjectInputStream(new ByteArrayInputStream(data));
			packet = (UdpPacket)iStream.readObject();
			iStream.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		catch (ClassNotFoundException e)
		{
			e.printStackTrace();
		}

		return packet;
	}

	public void Close()
	{
		if(client != null)
		{
			client.go = false;
		}
		
		if(server != null)
		{
			server.go = false;
		}
	}
}
